//
//  remarkViewController.m
//  MoneyLog
//
//  Created by wicresoft on 5/10/11.
//  Copyright 2011 wicresoft. All rights reserved.
//

#import "RemarkViewController.h"
#import "MappingViewController.h"
#import "RecordingViewController.h"
#import "ImageViewController.h"

@implementation RemarkViewController
@synthesize textView;

@synthesize locationManager;
@synthesize coordinate;
@synthesize locationButton;
@synthesize locationTargetButton;
@synthesize indecatorLocation;

@synthesize imageButton;
@synthesize recordImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [textView release];
    
    [locationButton release];
    [locationTargetButton release];
    [indecatorLocation release];
    [locationManager release];
    
    [imageButton release];
    [recordImageView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //create location manager
	locationManager = [[CLLocationManager alloc]init];
	locationManager.delegate = self;
	locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
//    if ( CLLocationCoordinate2DIsValid(coordinate)) {
//        locationTargetButton.hidden = NO;
//        locationButton.imageView.image = [UIImage imageNamed:@"Icon_location_1.png"];
//    }
//    else
//    {
//        locationTargetButton.hidden = YES;
//    }
//    
//    if (recordImage != nil) {
//        imageButton.imageView.image = [UIImage imageNamed:@"Icon_photo_1.png"];
//        imageViewButton.hidden = NO;
//        imageViewButton.imageView.image = self.recordImage;
//    }
//    else {
//        imageButton.imageView.image = [UIImage imageNamed:@"Icon_photo_0.png"];
//        imageViewButton.hidden = YES;
//
//    }
    
    indecatorLocation.hidden = YES;
    [textView becomeFirstResponder];
    
    recordImageView.userInteractionEnabled = YES;
    recordImageView.tag = 0xF01;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ( CLLocationCoordinate2DIsValid(coordinate)) {
        locationTargetButton.hidden = NO;
        [locationButton setBackgroundImage:[UIImage imageNamed:@"Icon_location_1.png"] forState:nil];
    }
    else {
        locationTargetButton.hidden = YES;
       [locationButton setBackgroundImage:[UIImage imageNamed:@"Icon_location_0.png"] forState:nil];
    }
    
    if (recordImageView.image != nil) {
        [imageButton setBackgroundImage:[UIImage imageNamed:@"Icon_photo_1.png"] forState:nil];
    }
    else {
        [imageButton setBackgroundImage:[UIImage imageNamed:@"Icon_photo_0.png"] forState:nil];
        
    }

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    
    if ([touch view].tag == 0xF01) {
        
        ImageViewController *controller = [[ImageViewController alloc] init];
        controller.image = self.recordImageView.image;
        controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self.navigationController presentModalViewController:controller animated:YES];
        [controller release];
    } 
}

#pragma mark -  * locationManager delegate

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"latitude = %f",newLocation.coordinate.latitude);
    NSLog(@"longitude = %f",newLocation.coordinate.longitude);
    
   if ( CLLocationCoordinate2DIsValid(coordinate)) {
   
       return;
   }
    
    indecatorLocation.hidden = YES;
    [indecatorLocation stopAnimating];
    
    locationTargetButton.hidden = NO;
    [locationButton setBackgroundImage:[UIImage imageNamed:@"Icon_location_1.png"] forState:nil];
    
	self.coordinate = newLocation.coordinate;
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
	NSString *errorString;
    
    indecatorLocation.hidden = YES;
    [indecatorLocation stopAnimating];
    
	if([error code] == kCLErrorDenied)
	{
		errorString = @"Access Not Allowed";
	}
	else if([error code] == kCLErrorLocationUnknown)
	{
		errorString = @"Unknown Error";
	}

	UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Cannot get location" 
                          message:errorString
                          delegate:nil
                          cancelButtonTitle:@"Close"
                          otherButtonTitles:nil];
	[alert show];
	[alert release];
}

#pragma mark - * UIImagePickerControllerDelegate method
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    self.recordImageView.image = nil;
    [imageButton setBackgroundImage:[UIImage imageNamed:@"Icon_photo_0.png"] forState:nil];
	[picker dismissModalViewControllerAnimated:YES];
    
    UIAlertView *alertView = [[UIAlertView alloc] 
                              initWithTitle:@"提示" 
                              message:@"选取图片失败！"
                              delegate:nil
                              cancelButtonTitle:@"确定"
                              otherButtonTitles:nil, nil];
    [alertView show];
    [alertView release];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
   // NSData *imageData = UIImagePNGRepresentation(image);
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [recordImageView setImage:image];
    [imageButton setBackgroundImage:[UIImage imageNamed:@"Icon_photo_1.png"] forState:nil];
	[picker dismissModalViewControllerAnimated:YES];
}


#pragma mark - * UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType sourceType;
    switch (buttonIndex) {
        case 0:
        {
            sourceType = UIImagePickerControllerSourceTypeCamera;
            break;
        }
        case 1:
        {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            break;
        }
        case 2:
        {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            break;
        }
        case 3:
        {
            return;
        }
        default:
            return;
    }
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
	if([UIImagePickerController isSourceTypeAvailable:sourceType])
	{
		imagePicker.sourceType = sourceType;
        imagePicker.allowsEditing=YES;
		//imagePicker.allowsImageEditing = YES;
		imagePicker.delegate = self;
		[self presentModalViewController:imagePicker animated:YES];
	}
	else
	{
		UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil
													   message:@"Camera not available!"
													  delegate:nil
											 cancelButtonTitle:@"Close"
											 otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
    
    [imagePicker release];
}

#pragma mark - * UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == kLocationAlertView) {
        if (buttonIndex ==1) {
            locationTargetButton.hidden = YES;
            [locationButton setBackgroundImage:[UIImage imageNamed:@"Icon_location_0.png"] forState:nil];
            
            self.coordinate = kCLLocationCoordinate2DInvalid; 
        }

    }
    else if(alertView.tag == kImageAlertView )
    {
        if (buttonIndex == 1) {
            [imageButton setBackgroundImage:[UIImage imageNamed:@"Icon_photo_0.png"] forState:nil];
            self.recordImageView.image = nil;
        }
    }
}

#pragma mark - * actions

-(IBAction) locationUpdate
{
    if (locationTargetButton.hidden) {
        [locationManager startUpdatingLocation];
        indecatorLocation.hidden = NO;
        [indecatorLocation startAnimating];
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] 
                                  initWithTitle:@"提示" 
                                  message:@"确认要取消地理位置信息吗？"
                                  delegate:self
                                  cancelButtonTitle:@"取消" otherButtonTitles:@"确定",
                                  nil];
        alertView.tag = kLocationAlertView;
        [alertView show];
        [alertView release];
    }    
}

-(IBAction) showMap
{
    if (!locationTargetButton.hidden) {
        if (CLLocationCoordinate2DIsValid(self.coordinate)) {
            mappingViewController *controller = [[mappingViewController alloc] init];
            controller.coordinate = self.coordinate;
            [self.navigationController pushViewController:controller animated:YES];
            [controller release];
        }
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] 
                                  initWithTitle:@"提示" 
                                  message:@"地理位置信息无效"
                                  delegate:nil
                                  cancelButtonTitle:@"确定" otherButtonTitles:nil,
                                  nil];
        [alertView show];
        [alertView release];
    }
}

-(IBAction) imagePicker
{
    if (self.recordImageView.image == nil) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                      initWithTitle:@"选取图片" 
                                      delegate:self 
                                      cancelButtonTitle:@"取消" 
                                      destructiveButtonTitle:@"相机"
                                      otherButtonTitles:@"相薄",@"胶卷",nil];
        [actionSheet showInView:[UIApplication sharedApplication].keyWindow]; 
        [actionSheet release];
    }
    else {
        UIAlertView *alertView = [[UIAlertView alloc] 
                                  initWithTitle:@"提示" 
                                  message:@"确认要删除图片吗？"
                                  delegate:self
                                  cancelButtonTitle:@"取消" otherButtonTitles:@"确定",
                                  nil];
        alertView.tag = kImageAlertView;
        [alertView show];
        [alertView release];

    }
}

-(IBAction) recording
{
	RecordingViewController *controller =[[RecordingViewController alloc] init];
	controller.modalTransitionStyle =UIModalTransitionStyleCoverVertical;
	UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:controller];
	[self.navigationController presentModalViewController:navigation animated:YES];
	[navigation release];
    [controller release];
	
}


@end
